package com.zondy.mapgis.android.activity;

import java.io.DataOutputStream;
import java.io.IOException;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;

import org.json.JSONException;
import org.json.JSONObject;

import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.WindowManager;
import android.widget.EditText;
import android.widget.TextView;

import com.zondy.dizhi.server.util.APPNetWork;
import com.zondy.dizhi.server.util.GsonUtil;
import com.zondy.mapgis.android.base.BaseActivity;
import com.zondy.mapgis.android.utils.DaoJiShi;
import com.zondy.mapgis.android.utils.DaoJiShi.DaoJiShiCallBack;
import com.zondy.mapgis.android.utils.DialogUtil;
import com.zondy.mapgis.android.utils.FileOperation;
import com.zondy.mapgis.explorer.R;

public class RegisterActivity extends BaseActivity implements OnClickListener
{
	private TextView mTitle = null;
	public EditText mUserNameEt = null;
	public EditText mRegisterCodeEt = null;
	public EditText mPasswordEt = null;
	public EditText mRegisterErrorEt = null;
	private DaoJiShi mDaojishi;

	public String mCodeResult = null;

	@Override
	protected void onCreate(Bundle savedInstanceState)
	{
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_register);
		// 透明状态栏
		getWindow().addFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);
		// 透明导航栏
		getWindow().addFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_NAVIGATION);

		initView();
		APPNetWork.checkNetState(this);
	}

	private void initView()
	{
		mTitle = (TextView) findViewById(R.id.title_text);
		mTitle.setText("注册");
		mUserNameEt = (EditText) findViewById(R.id.et_username);
		mRegisterCodeEt = (EditText) findViewById(R.id.et_registercode);
		mPasswordEt = (EditText) findViewById(R.id.et_password);
		mRegisterErrorEt = (EditText) findViewById(R.id.register_error_ets);
		mDaojishi = (DaoJiShi) findViewById(R.id.huoquyanzhengma_btn);
		mDaojishi.setDaojishicallback(daojishiCallBack);

		findViewById(R.id.register_btn).setOnClickListener(this);
		findViewById(R.id.huoquyanzhengma_btn).setOnClickListener(this);
	}

	private Handler mHander = new Handler()
	{
		public void handleMessage(android.os.Message msg)
		{
			switch (msg.what)
			{
			case 1:
				startActivity(new Intent(getApplicationContext(), LoginActivity.class));
				finish();
				break;
			case 0:
				mRegisterErrorEt.setVisibility(View.VISIBLE);
				mRegisterErrorEt.setText("连接服务器异常");
				break;
			case -14:
				mRegisterErrorEt.setVisibility(View.VISIBLE);
				mRegisterErrorEt.setText("手机格式不正确");
				break;
			case -15:
				mRegisterErrorEt.setVisibility(View.VISIBLE);
				mRegisterErrorEt.setText("参数不全");
				break;
			case -16:
				mRegisterErrorEt.setVisibility(View.VISIBLE);
				mRegisterErrorEt.setText("验证码不正确");
				break;
			case -4:
				mRegisterErrorEt.setVisibility(View.VISIBLE);
				mRegisterErrorEt.setText("邮箱格式不正确");
				break;
			case -5:
				mRegisterErrorEt.setVisibility(View.VISIBLE);
				mRegisterErrorEt.setText("不允许注册的用户类型");
				break;
			case -1:
				mRegisterErrorEt.setVisibility(View.VISIBLE);
				mRegisterErrorEt.setText("用户名已存在");
				break;

			default:
				break;
			}
		};

	};

	@Override
	public void onClick(View v)
	{
		switch (v.getId())
		{
		case R.id.register_btn:
			final String username = mUserNameEt.getText().toString().trim();
			final String password = mPasswordEt.getText().toString().trim();
			final String code = mRegisterCodeEt.getText().toString().trim();

			DialogUtil.createProgressDialog(this, "正在注册...", "注册");
			new Thread(new Runnable()
			{
				@Override
				public void run()
				{
					register(username, password, code);
				}
			}).start();
			break;

		default:
			break;
		}
	}
	
	DaoJiShiCallBack daojishiCallBack = new DaoJiShiCallBack()
	{
		@Override
		public boolean Start()
		{
			final String nameStr = mUserNameEt.getText().toString().trim();
			new Thread(new Runnable()
			{
				@Override
				public void run()
				{
					registerCode(nameStr);
				}
			}).start();
			return true;
		}

		@Override
		public void End()
		{
		}

		@Override
		public void numChanged(int num)
		{
		}
	};

	/**
	 * 获取验证码
	 * 
	 * @param nameStr
	 */
	private void registerCode(String nameStr)
	{
		HttpURLConnection connection = null;
		byte[] data = null;
		String strResult = null;

		URL postUrl;
		try
		{
			postUrl = new URL("http://www.smaryun.com/ucenter/user.php?a=sendRegCode");
			connection = (HttpURLConnection) postUrl.openConnection();
			connection.setDoOutput(true);
			connection.setDoInput(true);
			connection.setRequestMethod("POST");
			connection.setUseCaches(false);
			connection.setInstanceFollowRedirects(true);
			connection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
			connection.connect();
			DataOutputStream out = new DataOutputStream(connection.getOutputStream());
			String content = String.format("user=%s&remember=false&format=json", nameStr);
			out.writeBytes(content);
			out.flush();
			out.close();

			// 判断请求是否成功
			if (connection.getResponseCode() != 200)
			{
				return;
			}
			else
			{
				// 获取返回的数据
				data = FileOperation.InputStreamToByte(connection.getInputStream());
				// 关闭连接
				connection.disconnect();
			}
			strResult = GsonUtil.getBytesToString(data);
			JSONObject jsonObject = new JSONObject(strResult);
			mCodeResult = jsonObject.getString("result");

			Log.e("strResult:", mCodeResult);
		}
		catch (MalformedURLException e)
		{
			e.printStackTrace();
		}
		catch (IOException e)
		{
			e.printStackTrace();
		}
		catch (JSONException e)
		{
			e.printStackTrace();
		}
	}

	/**
	 * 注册
	 * 
	 * @param username
	 * @param password
	 * @param code
	 */
	private void register(String username, String password, String code)
	{

		HttpURLConnection connection = null;
		byte[] data = null;
		String strResult = null;
		Message msg = new Message();

		try
		{
			// Protocol not
			// found:www.smaryun.com/ucenter/user.php?a=register_by_code
			URL postUrl = new URL("http://www.smaryun.com/ucenter/user.php?a=register_by_code");
			connection = (HttpURLConnection) postUrl.openConnection();
			connection.setDoOutput(true);
			connection.setDoInput(true);
			connection.setRequestMethod("POST");
			connection.setUseCaches(false);
			connection.setInstanceFollowRedirects(true);
			connection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
			connection.connect();
			DataOutputStream out = new DataOutputStream(connection.getOutputStream());
			String content = String.format("username=%s&password=%s&code=%s&guid=%s&remember=false&format=json", username, password, code, mCodeResult);
			out.writeBytes(content);
			out.flush();
			out.close();

			// 判断请求是否成功
			if (connection.getResponseCode() != 200)
			{
				msg.what = 0;
				return;
			}
			else
			{
				// 获取返回的数据
				data = FileOperation.InputStreamToByte(connection.getInputStream());
				// 关闭连接
				connection.disconnect();
			}
			strResult = GsonUtil.getBytesToString(data);
			Log.e("strResult:", strResult);

			JSONObject jsonObject = new JSONObject(strResult);
			if (jsonObject.getString("success").equals(true))
			{
				msg.what = 1;
			}
			else
			{
				msg.what = jsonObject.getInt("result");
			}
		}
		catch (MalformedURLException e)
		{
			e.printStackTrace();
		}
		catch (IOException e)
		{
			msg.what = 0;
			e.printStackTrace();
		}
		catch (JSONException e)
		{
			e.printStackTrace();
		}

		DialogUtil.cancelProgressDialog();
		mHander.sendMessage(msg);

	}

	@Override
	public void onBackPressed()
	{
		super.onBackPressed();
	}
}
